// pages/orderDetail/orderDetail.js
var app = getApp();
const viewLogisticsUrl = '/Order/orderExpressInfo';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    express_number:'',//物流单号
    express_url:'',//物流地址
    isPaying: false, //是否正在支付
    isLoading: 1, //是否显示加载中图标
    // end_time:1542169389,//支付结束的时间戳
    is_self: 1, //判断是否为粉丝订单
    currentStatus: {}, //商品当前所处的位置
    isTransporting: 0, //判断是否在运输中
    isBargainSuccess: 0, //控制砍价支付成功的弹层显示
    is_shop_order: 0, //判断是否是购物车商品
    uid: 0, //用户的ID
    filesSourceUri: '', //存储静态资源文件地址
    freight: '', //到付运费
    goodsDetail: {}, //存储商品详情
    addressDetail: {}, //存储地址详情
    goods_level: 0, //订单类型
    is_use_enve: 0, //是否使用红包余额 0未使用 1使用
    payTitle: '', //支付金额标题
    payDetail: '', //支付金额详情
    payMoney: '', //需要支付的金额
    page: 1,
    recommendList: [],
    orderId: 0, //订单ID
    platform: '',
    order_money: '',
    isSelfCutMaskShow: 0,
  },
  // 关闭自己砍价成功的弹层
  closeSelfCutMask: function() {
    var _this = this;
    _this.setData({
      isSelfCutMaskShow: 0
    });

  },
  // 关闭订单
  closeOrder: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    wx.showModal({
      title: '订单关闭提示',
      content: '确定要关闭当前订单吗',
      success(res) {
        if (res.confirm) {
          var goodsDetail = _this.data.goodsDetail;
          var requestData = {
            token: _this.data.token,
            version: app.setConfig.version,
            type: app.setConfig.type,
            order_id: _this.data.orderId
          }
          app.post('/order/closeOrder', requestData, function (res) {
            if (res.code == 2000) {
              goodsDetail.order_status = 9;
              goodsDetail.is_show_end_tm = 0;
              _this.setData({
                goodsDetail: goodsDetail
              })
              wx.showToast({
                title: '关闭订单成功',
                icon: 'success',
                duration: 2000
              })
            } else {
              wx.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
              })
            }
          });
        } else if (res.cancel) {
          
        }
      }
    })
    
  },
  // 跳转商品详情页
  goDetail: function(e) {
    var _this = this;
    var theGoodsId = e.currentTarget.dataset.goods_id;
    wx.navigateTo({
      url: '/pages/goodsDetail/goodsDetail?goodsId=' + theGoodsId,
    })
  },
  // 确认参与抽奖
  sureJoin: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    var goodsDetail = _this.data.goodsDetail;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      order_id: _this.data.orderId
    }
    app.post('/Order/joinLucky', requestData, function(res) {
      if (res.code == 2000) {
        goodsDetail.is_join = 1;
        _this.setData({
          goodsDetail: goodsDetail
        })
        wx.showToast({
          title: '参与抽奖成功',
          icon: 'success',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  // 申请发货
  deliverGood: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    var goodsDetail = _this.data.goodsDetail;
    wx.showModal({
      title: '确定申请发货',
      content: '在收到东西时，需要您承担快递费用',
      success: function(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          goodsDetail.order_status = 2;
          goodsDetail.is_apply_send = 1,
            _this.setData({
              goodsDetail: goodsDetail
            })
          _this.applySendGoods();
        } else if (res.cancel) {}
      }
    })
  },
  // 申请发货调用接口
  applySendGoods: function(e) {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      order_id: _this.data.orderId
    }
    app.post('/Order/applySendGoods', requestData, function(res) {
      if (res.code == 2000) {
        wx.showToast({
          title: '成功收货',
          icon: 'success',
          duration: 2000,
          success: function() {
            _this.getOrderDetail();
          }
        })
      }else{
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    });
  },
  // 跳转物流详情页
  goLogistics: function() {
    var _this = this;
    var express_url = _this.data.express_url + _this.data.express_number;
    console.log(express_url);
    wx.navigateTo({
      url: '/pages/logistics/logistics?order_id=' + _this.data.orderId
    })
  },
  // 跳转砍价页面
  goBargain: function() {
    var _this = this;
    wx.navigateTo({
      url: '/pages/bargain/bargain?uid=' + _this.data.uid + '&order_id=' + _this.data.orderId,
    })
  },
  // 跳转抽奖页面
  goDraw:function(){
    var _this = this;
    wx.navigateTo({
      url: '/pages/draw/draw?uid=' + _this.data.uid + '&order_id=' + _this.data.orderId,
    })
  },
  // 跳转现金券列表页面
  goCouponList: function () {
    var _this = this;
    wx.navigateTo({
      url: '/pages/couponList/couponList',
    })
  },
  // 返回首页
  goHome: function() {
    var _this = this;
    wx.reLaunch({
      url: '/pages/home/home',
    })
  },
  // 免费领按钮
  freeReceive: function(e) {
    var _this = this;
    var theGoodsId = e.currentTarget.dataset.goods_id;
    wx.navigateTo({
      url: '/pages/goodsDetail/goodsDetail?goodsId=' + theGoodsId,
    })
  },
  // 点击完成按钮
  completed: function() {},
  // 去往地址列表页设置收货地址
  goSetAddress: function() {
    var _this = this;
    var orderId = _this.data.orderId;
    var goodsDetail = _this.data.goodsDetail;
    if (goodsDetail.order_status < 3) {
      wx.navigateTo({
        url: '/pages/addressList/addressList?orderId=' + orderId,
      })
    } else {
      wx.showToast({
        title: '商品已发货，不可修改地址',
        icon: 'none'
      })
    }

  },
  // 确认收货
  confirmReceipt: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);

    var requestData = {
      token: _this.data.token,
      order_id: _this.data.orderId
    }
    app.post('/Order/takeGoods', requestData, function(res) {
      if (res.code == 2000) {
        var goodsDetail = _this.data.goodsDetail;
        goodsDetail.order_status = 3;
        _this.setData({
          goodsDetail: goodsDetail
        })
        wx.showToast({
          title: '成功收货',
          icon: 'success',
          duration: 2000,
          success: function() {
            _this.getOrderDetail();
          }
        })
      }else{
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    });
  },
  // 获取订单详情
  getOrderDetail: function() {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      order_id: _this.data.orderId,
      uid: _this.data.uid
    }
    app.post('/Order/detail', requestData, function(res) {
      if (res.code == 2000) {
        var goods = res.data.goods,
          payTitle, payDetail, payMoney;
        var goodsLevel = res.data.goods.goods_level;
        var goodsDetail = res.data.goods;
        if (goodsDetail.list) {
          var goodsList = goodsDetail.list;
          for (var i = 0; i < goodsList.length; i++) {
            goodsList[i].carousel_img = _this.data.filesSourceUri + '/' + JSON.parse(goodsList[i].carousel_img);
          }
        }
        if (res.data.goods.is_self == 0) {
          wx.setNavigationBarTitle({
            title: '粉丝订单'
          })
        }
        _this.setData({
          isLoading: 0,
          is_show_end_tm: res.data.goods.is_show_end_tm,
          end_time: res.data.goods.end_tm,
          is_self: res.data.goods.is_self,
          goods_level: goodsLevel,
          addressDetail: res.data.address,
          goodsDetail: goodsDetail,
          is_shop_order: res.data.is_shop_order,
          express_number: res.data.express.express_number,
          express_url: res.data.express.express_url
        });
        // 版本一的订单详情页的逻辑
        if (goodsLevel != 4) {
          _this.setData({
            order_type: goods.order_type
          })
          if (goods.order_type == 0) {
            if (goods.enve_is_used == 1) {
              _this.setData({
                is_use_enve: 1,
                payMoney: goods.pay_enve_money,
                payTitle: '支付' + goods.pay_enve_money + '元',
                payDetail: '付款金额=' + '商品' + goods.goods_money + '×' + goods.goods_num + '元' + '-余额抵扣' + goods.deduction_money + '元' + '+运费' + goods.freight_money + '元'
              })
            } else {
              if (goods.is_show_freight == 1) {
                _this.setData({
                  payMoney: goods.freight_money,
                  payTitle: '支付' + goods.freight_money + '元运费',
                  payDetail: '',
                })
              } else {
                _this.setData({
                  payMoney: goods.pay_money,
                  payTitle: '支付' + goods.pay_money + '元',
                  payDetail: '付款金额=' + '商品' + goods.goods_money + '×' + goods.goods_num + '元' + '+运费' + goods.freight_money + '元'
                })
              }

            }

          } else {
            _this.setData({
              payMoney: goods.freight_money,
              payTitle: '支付' + goods.freight_money + '元运费',
              payDetail: ''
            })
          }
          if (!goods.order_money) {
            if (goods.is_use_enve == 1 && goods.order_status == 0) {
              wx.showModal({
                title: '是否使用余额抵扣',
                content: '使用余额可抵扣' + goods.deduction_money + '元商品价格',
                cancelText: '不使用',
                confirmText: '使用',
                success: function(res) {
                  // 使用余额支付
                  if (res.confirm) {
                    console.log('使用');
                    _this.setData({
                      is_use_enve: 1,
                      payMoney: goods.pay_enve_money,
                      payTitle: '支付' + goods.pay_enve_money + '元',
                      payDetail: '付款金额=' + '商品' + goods.goods_money + '×' + goods.goods_num + '元' + '-余额抵扣' + goods.deduction_money + '元' + '+运费' + goods.freight_money + '元'
                    })
                  }
                  if (res.cancel) {
                    _this.setData({
                      is_use_enve: 0
                    });
                    console.log('不使用');
                  }
                }
              })
            }
          }
        } else {
          // 版本二的数据结构
          /*
          is_platform判断是否是平台发布的
          is_draw判断是否是抽奖的
          
           */
          var is_platform = res.data.goods.is_platform;
          var is_draw = res.data.goods.is_draw;
          // 平台发布的商品
          if (is_platform == 1) {
            if (is_draw == 0) {
              // 普通商品
              _this.setData({
                payMoney: goods.pay_money,
                payTitle: '支付' + goods.pay_money + '元',
                payDetail: '付款金额=' + '商品' + goods.goods_money + '×' + goods.goods_num + '元' + '+运费' + goods.freight_money + '元',

              })
            } else {
              // 抽奖商品
              _this.setData({
                freight: res.data.goods.pay_money
              })
            }
          } else {
            // 个人对个人的商品
            var payMoney = goods.pay_money;
            // 需要支付的钱为0的时候
            if (payMoney == 0) {
              _this.setData({
                freight: res.data.goods.pay_money
              })
            } else {
              // 需要支付的钱不为0的时候
              console.log(goods);
              var payMoney = goods.pay_money;
              _this.setData({
                payMoney: payMoney,
                payTitle: '支付' + goods.pay_money + '元',
                payDetail: '付款金额=' + '商品' + goods.goods_money + '×' + goods.goods_num + '元' + '+运费' + goods.freight_money + '元'
              })
            }

          }
        }
        _this.getRecommendList();
        if (res.data.goods.is_show_end_tm == 1) {
          _this.bargainCountDown();
        }
        if (res.data.is_express == 1) {
          _this.viewLogistics();
          _this.setData({
            isTransporting: 1
          })

        }
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'loading',
          duration: 2000
        })
      }
    })
  },
  // 查看物流接口
  viewLogistics: function() {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      order_id: _this.data.orderId
    }
    app.post(viewLogisticsUrl, requestData, function(res) {
      if (res.message != 'ok') {
        _this.setData({
          isTransporting: 0
        })
      } else {
        _this.setData({
          currentStatus: res.data[0]
        })
      }

    });
  },
  // 获取商品推荐列表
  getRecommendList: function() {
    var _this = this;
    var keywords = _this.data.goodsDetail.goods_name;
    if (!keywords) {
      keywords = _this.data.goodsDetail.list[0].goods_name
    }

    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      keywords: keywords,
      search_type: 0,
      page: _this.data.page
    }
    app.post('/Goods/recommend', requestData, function(res) {
      if (res.code == 2000) {
        wx.hideNavigationBarLoading(); //完成停止加载
        wx.stopPullDownRefresh(); //停止下拉刷新
        var recommendList = _this.data.recommendList;
        var configs = wx.getStorageSync('configs');
        for (var i = 0; i < res.data.list.length; i++) {
          res.data.list[i].img = configs.static_url_http + '/' + res.data.list[i].img;
        }
        recommendList = recommendList.concat(res.data.list);
        _this.setData({
          page: res.data.page,
          recommendList: recommendList
        })
      }else{
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    });
  },
  // 支付商品费用
  payForcost: function(e) {
    var _this = this;
    _this.setData({
      isPaying: true,
    })
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    var requestData = {
      token: _this.data.token,
      money: _this.data.payMoney,
      is_use_enve: _this.data.is_use_enve,
      order_id: _this.data.goodsDetail.order_id
    }
    app.post('/Recharge/goPayOrder', requestData, function(res) {
      console.log(res);
      var goodsDetail = _this.data.goodsDetail;
      if (res.code == 2000) {
        if (e.currentTarget.dataset.pay_type == 1) {
          var goodsDetail = _this.data.goodsDetail;
          goodsDetail.order_status = 2;
          _this.setData({
            isPaying: true,
            isSelfCutMaskShow: 1,
            isBargainSuccess: 1,
            goodsDetail: goodsDetail
          })
        }
        var payInfo = res.data;
        if (payInfo.respay) {
          wx.requestPayment({
            'timeStamp': payInfo.respay.timeStamp,
            'nonceStr': payInfo.respay.nonceStr,
            'package': payInfo.respay.package,
            'signType': 'MD5',
            'paySign': payInfo.respay.paySign,
            'success': function(res) {
              goodsDetail.order_status = 2,
                _this.setData({
                  isSelfCutMaskShow: 1,
                  isBargainSuccess: 1,
                  goodsDetail: goodsDetail,
                  isBalancePaymentShow: 0,
                  isOpend: 1
                });
            },
            'fail': function(res) {
              goodsDetail.order_status = 0,
                _this.setData({
                  isSelfCutMaskShow: 0,
                  isBargainSuccess: 0,
                  goodsDetail: goodsDetail
                });
            },
            'complete': function(res) {
              _this.setData({
                isPaying: false,
              })
            }
          });
        } else {
          goodsDetail.order_status = 2,
            _this.setData({
              isSelfCutMaskShow: 1,
              isBargainSuccess: 1,
              goodsDetail: goodsDetail
            })
          wx.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 1500
          })
        }

      } else {
        _this.setData({
          isPaying: false,
        });
        wx.showToast({
          title: res.msg,
          icon: 'loading',
          mask: true,
          duration: 1500
        });
      }
    });
  },
  // 支付砍价金额
  payForBargain: function(e) {
    var _this = this;
    _this.setData({
      isPaying: true,
    });
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      order_id: _this.data.goodsDetail.order_id
    }
    app.post('/Bargain/payOrder', requestData, function(res) {
      var goodsDetail = _this.data.goodsDetail;
      if (res.code == 2000) {
        var payInfo = res.data;
        if (payInfo.respay) {
          wx.requestPayment({
            'timeStamp': payInfo.respay.timeStamp,
            'nonceStr': payInfo.respay.nonceStr,
            'package': payInfo.respay.package,
            'signType': 'MD5',
            'paySign': payInfo.respay.paySign,
            'success': function(res) {
              _this.setData({
                isPaying: true,
                isSelfCutMaskShow: 1,
                isBargainSuccess: 1,
                isOpend: 1
              });
            },
            'fail': function(res) {

            },
            'complete': function(res) {
              _this.setData({
                isPaying: false,
              });
            }
          });
        } else {
          _this.setData({
            isPaying: false,
            isSelfCutMaskShow: 1,
            isBargainSuccess: 1
          })
          wx.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 1500
          })
        }

      } else {
        _this.setData({
          isPaying: false,
        });
        wx.showToast({
          title: res.msg,
          icon: 'loading',
          mask: true,
          duration: 1500
        });
      }
    });
  },
  // 支付抽奖金额
  payForDraw: function (e) {
    var _this = this;
    _this.setData({
      isPaying: true,
    });
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      order_id: _this.data.goodsDetail.order_id
    }
    app.post('/Draw/payOrder', requestData, function (res) {
      var goodsDetail = _this.data.goodsDetail;
      if (res.code == 2000) {
        var payInfo = res.data;
        if (payInfo.respay) {
          wx.requestPayment({
            'timeStamp': payInfo.respay.timeStamp,
            'nonceStr': payInfo.respay.nonceStr,
            'package': payInfo.respay.package,
            'signType': 'MD5',
            'paySign': payInfo.respay.paySign,
            'success': function (res) {
              _this.setData({
                isPaying: true,
                isSelfCutMaskShow: 1,
                isBargainSuccess: 1,
                isOpend: 1
              });
            },
            'fail': function (res) {

            },
            'complete': function (res) {
              _this.setData({
                isPaying: false,
              });
            }
          });
        } else {
          _this.setData({
            isPaying: false,
            isSelfCutMaskShow: 1,
            isBargainSuccess: 1
          })
          wx.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 1500
          })
        }

      } else {
        _this.setData({
          isPaying: false,
        });
        wx.showToast({
          title: res.msg,
          icon: 'loading',
          mask: true,
          duration: 1500
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _this = this;
    wx.getSystemInfo({
      success: function(res) {
        _this.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight,
          platform: res.platform
        })
      },
    })
    if (options.uid) {
      _this.setData({
        uid: options.uid
      });
    }
    var configs = wx.getStorageSync('configs');
    _this.setData({
      filesSourceUri: configs.static_url_http,
      orderId: options.orderId
    });
  },
  // 判断是否获取到token的值了
  loop: function() {
    var _this = this;
    var theToken = wx.getStorageSync("token");
    var theRegionUnit = _this.data.regionUnit;
    if (!theToken) {
      setTimeout(function() {
        _this.loop()
      }, 100);
    } else {
      _this.setData({
        token: theToken
      });
      _this.getOrderDetail();
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

    var _this = this;
    _this.loop();
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    var _this = this;
    wx.showNavigationBarLoading() //在标题栏中显示加载
    _this.setData({
      page: 1,
      recommendList: []
    })
    _this.getRecommendList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var _this = this;
    // console.log('1');
    _this.getRecommendList();
  },
  // 砍价倒计时
  bargainCountDown: function() {
    var _this = this;
    var end_time = _this.data.goodsDetail.end_tm;
    var totalSecond = end_time - Date.parse(new Date()) / 1000;

    var interval = setInterval(function() {
      // 秒数
      var second = totalSecond;

      // 天数位
      var day = Math.floor(second / 3600 / 24);
      var dayStr = day.toString();
      if (dayStr.length == 1) dayStr = '0' + dayStr;

      // 小时位
      var hr = Math.floor((second - day * 3600 * 24) / 3600);
      var hrStr = hr.toString();
      if (hrStr.length == 1) hrStr = '0' + hrStr;

      // 分钟位
      var min = Math.floor((second - day * 3600 * 24 - hr * 3600) / 60);
      var minStr = min.toString();
      if (minStr.length == 1) minStr = '0' + minStr;

      // 秒位
      var sec = second - day * 3600 * 24 - hr * 3600 - min * 60;
      var secStr = sec.toString();
      if (secStr.length == 1) secStr = '0' + secStr;

      this.setData({
        countDownDay: dayStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
      });
      totalSecond--;
      if (totalSecond < 0) {
        clearInterval(interval);
        _this.setData({
          auction_status: 2
        })
        this.setData({
          countDownDay: '00',
          countDownHour: '00',
          countDownMinute: '00',
          countDownSecond: '00',
        });
      }
    }.bind(this), 1000);
  }
})